// pages/bank-id-card/bank-id-card.js
import global from '../../utils/global'
import user from '../../utils/user'
const app = getApp()
import {
    insertBankCardNo
} from '../../api/app'
import {
    wxfileTobase64
} from '../../utils/util'
import {
    register,
    distinguishIdCard, // 实名认证 点击身份证识别身份证信息
    getEcho, // 用户信息回显
    encryptedPhoneData
} from '../../api/app.js'
import bankList from '../../utils/bankList.js';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        bank_card: "",
        bank_cardaddress: "",
        showbankcardaddressflag: false,
        dataInformation: {},
        userName: '',
        idCardNo: '',
        ownIdCardBack: '',
        ownIdCardFront: '',
        bankcardok: false,
        idcardok: false,
        allisok: false,
        isCollectOpenBankAddressflag: false,
        isCollectOpenBankName: true,
        isCollectOpenBankCity: true,
        error: '',
        formData: {
            name: '',
            bankCard: '',
            openBank: '',
            branchBank: '',
            region: [],
            regionId: [],
            bankIndex: '',
            bankCardurl: ''
        },
        rules: [{
                name: 'bankCard',
                rules: [{
                        required: true,
                        message: '请输入银行卡号'
                    },
                    {
                        validator: function (rule, value, param, modeels) {
                            let bank_reg = /^[1-9]\d{9,29}$/
                            if (value.replace(/\s*/g, "").length < 16 || value.replace(/\s*/g, "").length > 19) {
                                return '银行卡号码不得低于16位，不得高于19位'
                            }
                            if (bank_reg.test(value.replace(/\s*/g, "")) === false) {
                                return '请输入正确的银行卡号'
                            }
                        }
                    }
                ]
            },
            // {
            //     name: "openBank",
            //     rules: [
            //         {
            //             required: true,
            //             message: '请选择开户银行'
            //         }
            //     ]
            // },
            // {
            //     name: "branchBank",
            //     rules: [
            //         {
            //             required: true,
            //             message: '请输入开户行支行'
            //         }
            //     ]
            // },
            // {
            //     name: "region",
            //     rules: [
            //         {
            //             validator: function (rule, value, param, modeels) {
            //                 if (!value?.length) {
            //                     return '请选择开户城市'
            //                 }
            //             }
            //         }
            //     ]
            // },
        ],
        curBank: {},
        bankArray: bankList,
        showBankList: false,
        searchBankName: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log(options, 'options1');
        this.setData({
            showbankcardaddressflag: options.isshowCollectOpenBankAddress === 0 ? false : true,
            isCollectOpenBankName: !(options.isCollectOpenBankName === '0'),
            isCollectOpenBankCity: !(options.isCollectOpenBankCity === '0'),
            from: options.from || '',
            ['formData.name']: user.userName
        })

        if (options.isCollectOpenBankName === '1') {
            this.data.rules.push({
                    name: "openBank",
                    rules: [{
                        required: true,
                        message: '请选择开户银行'
                    }]
                },
                //   {
                // 	  name: "branchBank",
                // 	  rules: [
                // 		  {
                // 			  required: true,
                // 			  message: '请输入开户行支行'
                // 		  }
                // 	  ]
                //   }
            )
        }

        if (options.isCollectOpenBankCity === '1') {
            this.data.rules.push({
                name: "region",
                rules: [{
                    validator: function (rule, value, param, modeels) {
                        if (!value?.length) {
                            return '请选择开户城市'
                        }
                    }
                }]
            })
        }
        this.setData({
            rules: this.data.rules
        })
        this.getEcho()
    },
    async submitbankandidcard() {
        console.log('调用提交基本信息身份证以及银行卡');
        await this.register()
        await this.onEditInsertBankCardNo()
        if (this.data.idcardok && this.data.bankcardok) {
            setTimeout(() => {
                wx.navigateBack()
            }, 1000)
        }
    },
    clearnbankcard() {
        console.log('清空银行卡号输入框');
        this.setData({
            bank_card: ""
        })
    },
    clearnbankcardaddress() {
        console.log('清空银行卡号输入框');
        this.setData({
            bank_cardaddress: ""
        })
    },
    // 提交银行卡
    async onEditInsertBankCardNo() {
        this.selectComponent('#form').validate(async (valid, errors) => {
            if (!valid) {
                const firstError = Object.keys(errors)
                if (firstError.length) {
                    // this.setData({
                    //     error: errors[firstError[0]].message
                    // })
                    app.toast(errors[firstError[0]].message)
                }
            } else {
                await insertBankCardNo({
                    userName: this.data.formData.name,
                    bankCardNo: this.data.formData.bankCard.replace(/\s*/g, "") || null,
                    openBankAddress: this.data.formData.openBank || null,
                    openBankName: this.data.formData.openBank || null,
                    openBankBranch: this.data.formData.branchBank || null,
                    openBankCity: this.data.formData.region?.length ? this.data.formData.region.join(',') : null,
                    bankCardImg: this.data.formData.bankCardurl,
                })
                app.toast('提交成功')
                this.data.bankcardok = true
                user.bankCardNo = this.data.bank_card.replace(/\s*/g, "")
            }
        })
        return
        let bank_reg = /^[1-9]\d{9,29}$/
        if (!this.data.bank_card.replace(/\s*/g, "")) {
            await app.toast('请输入银行卡号码')
            return
        }
        if (this.data.bank_card.replace(/\s*/g, "").length < 16 || this.data.bank_card.replace(/\s*/g, "").length > 19) {
            await app.toast('银行卡号码不得低于16位，不得高于19位')
            return
        }
        if (bank_reg.test(this.data.bank_card.replace(/\s*/g, "")) === false) {
            await app.toast('请输入正确的银行卡号')
            return
        }
        if (this.data.showbankcardaddressflag && this.data.bank_cardaddress === '') {
            await app.toast('请输入银行卡开户行地址')
            return
        }
        await insertBankCardNo({
            bankCardNo: this.data.bank_card.replace(/\s*/g, ""),
            openBankAddress: this.data.bank_cardaddress === '' ? null : this.data.bank_cardaddress,
        })
        app.toast('提交成功')
        this.data.bankcardok = true
        user.bankCardNo = this.data.bank_card.replace(/\s*/g, "")
    },
    // 提交身份证正反面
    async register() {
        this.data.dataInformation.openId = user.openid
        this.data.dataInformation.userHeadUrl = user.avatarUrl
        this.data.dataInformation.bankCardIs = 1
        this.data.dataInformation.userName = this.data.dataInformation.userName.replace(/\s*/g, '')
        this.data.dataInformation.isOpenSalaryCard = Number(this.data.goRelation)
        console.log(this.data.dataInformation, 'prevPage')
        const result = await register(this.data.dataInformation)
        if (result === 'needPhoto') {
            app.toast('您的身份信息校验失败，请上传您的身份照片后重试')
            this.setData({
                isEdit: true
            })
            return
        }
        app.toast('提交身份信息成功')
        this.data.idcardok = true
        console.log(app.globalData, 'app.globalData')
        await user.reLogin()
    },
    // input监听并改变绑定值
    iptchange(e) {
        const {
            value
        } = e.detail
        this.setData({
            bank_card: value.replace(/\s/g, '').replace(/....(?!$)/g, '$& ')
        })
    },
    iptaddresschange(e) {
        const {
            value
        } = e.detail
        this.setData({
            bank_cardaddress: value
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },
    async getEcho() {
        console.log('调用啦吗')
        await user.waitLogin()
        const result = await getEcho()
        console.log(result, 'result')
        this.setData({
            dataInformation: result,
        })
    },
    async onBankCard() {
        wx.navigateTo({
            url: '/pages/demo/demo?type=' + '3',
            events: {
                BankCard: async (base64) => {
                    this.setData({
                        ['dataInformation.bankcardurl']: base64.url
                    })
                    wx.uploadFile({
                        url: global.baseUrl + '/api/v1/blue/user/upload',
                        filePath: base64.url,
                        name: 'file',
                        formData: {
                            'user': 'test'
                        },
                        success: (res) => {
                            const data = res.data
                            console.log(JSON.parse(data).data.fileUrl);
                            this.setData({
                                ['formData.bankCardurl']: JSON.parse(data).data.fileUrl
                            })
                        }
                    })
                }
            }
        })
    },
    async onEditCardback() {
        wx.navigateTo({
            url: '/pages/demo/demo?type=' + '2',
            events: {
                idCard: async (base64) => {
                    const result = await distinguishIdCard({
                        idCard: base64.base64
                    })
                    this.setData({
                        ['dataInformation.ownIdCardBack']: result.data.url
                    })
                }
            }
        })
    },
    // 上传图片
    async onEditCard() {
        wx.navigateTo({
            url: '/pages/demo/demo?type=' + '1',
            events: {
                idCard: async (base64) => {
                    const result = await distinguishIdCard({
                        idCard: base64.base64
                    })
                    if (this.data.dataInformation.userName == '' || this.data.dataInformation.idCardNo == '') {
                        this.setData({
                            ['dataInformation.userName']: result.data.idCardInfo.name,
                            ['dataInformation.idCardNo']: result.data.idCardInfo.code,
                            ['dataInformation.ownIdCardFront']: result.data.url,
                            judgeId: false
                        })
                        return 0
                    }
                    if (result.data.idCardInfo.name == this.data.dataInformation.userName || result.data.idCardInfo.code == this.data.dataInformation.idCardNo) {
                        this.setData({
                            ['dataInformation.userName']: result.data.idCardInfo.name,
                            ['dataInformation.idCardNo']: result.data.idCardInfo.code,
                            ['dataInformation.ownIdCardFront']: result.data.url,
                            judgeId: false
                        })
                    } else {
                        app.alert('身份证照片和当前身份信息不符')
                    }
                }
            }
        })
    },
    handleFocus(ev) {
        this.setData({
            showBankList: true
        })
    },
    handleOpenBank(ev) {
        wx.navigateTo({
            url: '/pages/bank-list/bank-list',
            events: {
                bankName: (data) => {
                    if (data?.name) {
                        this.setData({
                            'formData.openBank': data.name
                        })
                    }
                }
            },
            // success(res) {
            //   res.eventChannel.on('selectBank', (data) => {
            //     console.log(1111, data);
            //   })
            // }
        })
    },
    handleBankCardInput(ev) {
        this.setData({
            'formData.bankCard': ev.detail.value
        })
    },
    handleBranchBankInput(ev) {
        this.setData({
            'formData.branchBank': ev.detail.value
        })
    },
    bindBankChange(ev) {
        this.setData({
            'formData.bankIndex': ev.detail.value,
            'formData.openBank': this.data.bankArray[ev.detail.value].name,
            curBank: this.data.bankArray[ev.detail.value]
        })
    },
    bindRegionChange(ev) {
        this.setData({
            'formData.region': ev.detail.value,
            'formData.regionId': ev.detail.code
        })
    },
    handleSelect(ev) {
        const value = ev.target.dataset
        this.setData({
            'formData.openBank': value.name,
            showBankList: false
        })
    },
    handleSearch(ev) {
        const value = ev.detail.value
        let list = bankList
        if (value) {
            list = bankList.filter(i => i.name.includes(value))
        }
        this.setData({
            bankArray: list,
            searchBankName: value
        })
    },
    setBankName(ev) {
        this.setData({
            'formData.openBank': this.data.searchBankName,
            showBankList: false
        })
    },
    handleInit() {
        this.setData({
            searchBankName: '',
            bankArray: bankList
        })
    },
    onDeleteCard(ev) {
        this.setData({
            'formData.bankCard': ''
        })
    },
    onDeleteBranchCard(ev) {
        this.setData({
            'formData.branchBank': ''
        })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})